// ==UserScript==
// @name         跳转115播放页
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://webapi.115.com/*
// @include      https://webapi.115.com/files/search
// @icon         https://www.google.com/s2/favicons?sz=64&domain=115.com
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    // alert('跳转115播放页');

    function getQueryParam(param) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(param);
    }

    function regexCode(code){
        let regexStr = code;
        let numbers = code.match(/\d+/g);
        let chars = code.match(/[a-zA-Z]+/g);

        if (numbers && chars){
            regexStr = chars[0] + "-?" + numbers[0];
        }

        return new RegExp(regexStr, "gi");
    }

    function startJump(){
        let res = document.body.innerText;
        let resultJson = JSON.parse(res);
        if (!resultJson) return;

        let code = getQueryParam("search_value");
        let pickcode = null;
        let cid = null;

        if (resultJson.count > 0) {
            let reg = regexCode(code);
            for (let i = 0; i < resultJson.data.length; i++) {
                let row = resultJson.data[i];
                if (row.play_long && (row.n.search(reg) >= 0)) { //iv vdi ico play_long
                    pickcode = row.pc;
                    cid = row.cid

                    break;
                }
            }
        }

        if (!pickcode){
            alert('没有找到code： ' + code);
            return;
        }

        let playAddr = `https://115vod.com/?pickcode=${pickcode}`;
        let dirAddr = `https://115.com/?cid=${cid}&offset=0&mode=wangpan`;

        window.location.href = playAddr;

        // var newWindow = window.open(playAddr, '_blank'); // 在新标签页中打开URL
        // if (!newWindow) {
        //     // 窗口可能被浏览器阻止了
        //     alert('请允许浏览器打开新窗口或标签页。');
        // }
    }

    startJump();


})();